import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:url_launcher/url_launcher.dart';
import '../models/task.dart';
import '../theme/app_theme.dart';
import 'about_us_page.dart';
import 'edit_profile_page.dart';
import 'notification_settings_page.dart';
import 'category_tasks_page.dart';
import '../widgets/profile/task_category_grid.dart';
import '../widgets/profile/stats_overview.dart';

class ProfilePage extends StatefulWidget {
  final List<Task> tasks;
  
  const ProfilePage({
    Key? key,
    required this.tasks,
  }) : super(key: key);

  @override
  _ProfilePageState createState() => _ProfilePageState();
}

class _ProfilePageState extends State<ProfilePage> with TickerProviderStateMixin {
  // 用户信息
  String _userName = "steven";
  String _userEmail = "SteveJob@gmail.com";
  String _avatarPath = 'assets/images/touxiang.png';
  
  // 动画控制器
  late AnimationController _animationController;
  late AnimationController _profileAnimationController;
  late Animation<double> _fadeAnimation;
  late Animation<Offset> _slideAnimation;
  late Animation<double> _scaleAnimation;
  late Animation<double> _profileScaleAnimation;

  @override
  void initState() {
    super.initState();
    _initAnimations();
  }
  
  void _initAnimations() {
    _animationController = AnimationController(
      duration: const Duration(milliseconds: 1500),
      vsync: this,
    );
    
    _profileAnimationController = AnimationController(
      duration: const Duration(milliseconds: 1200),
      vsync: this,
    );
    
    _fadeAnimation = Tween<double>(
      begin: 0.0,
      end: 1.0,
    ).animate(CurvedAnimation(
      parent: _animationController,
      curve: const Interval(0.0, 0.6, curve: Curves.easeOut),
    ));
    
    _slideAnimation = Tween<Offset>(
      begin: const Offset(0, 0.5),
      end: Offset.zero,
    ).animate(CurvedAnimation(
      parent: _animationController,
      curve: const Interval(0.2, 0.8, curve: Curves.easeOutCubic),
    ));
    
    _scaleAnimation = Tween<double>(
      begin: 0.8,
      end: 1.0,
    ).animate(CurvedAnimation(
      parent: _animationController,
      curve: const Interval(0.4, 1.0, curve: Curves.elasticOut),
    ));
    
    _profileScaleAnimation = Tween<double>(
      begin: 0.0,
      end: 1.0,
    ).animate(CurvedAnimation(
      parent: _profileAnimationController,
      curve: Curves.elasticOut,
    ));
    
    // 启动动画
    _animationController.forward();
    _profileAnimationController.forward();
  }
  
  @override
  void dispose() {
    _animationController.dispose();
    _profileAnimationController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        decoration: const BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment.topCenter,
            end: Alignment.bottomCenter,
            colors: [
              Color(0xFFF8FAFC),
              Color(0xFFE2E8F0),
            ],
          ),
        ),
        child: SafeArea(
          child: AnimatedBuilder(
            animation: _animationController,
            builder: (context, child) {
              return FadeTransition(
                opacity: _fadeAnimation,
                child: SlideTransition(
                  position: _slideAnimation,
                  child: SingleChildScrollView(
                    child: Padding(
                      padding: const EdgeInsets.all(AppTheme.paddingL),
                      child: Column(
                        children: [
                          // 顶部装饰区域
                          _buildTopDecoration(),
                          
                          // 用户资料卡
                          ScaleTransition(
                            scale: _profileScaleAnimation,
                            child: _buildUserProfileCard(),
                          ),
                          
                          // 统计概览
                          ScaleTransition(
                            scale: _scaleAnimation,
                            child: _buildStatsOverview(),
                          ),
                          
                          // 任务分类
                          _buildTaskCategories(context),

                          // 设置区域
                          _buildSettingsSection(),
                          
                          // 底部间距
                          const SizedBox(height: AppTheme.paddingXXL),
                        ],
                      ),
                    ),
                  ),
                ),
              );
            },
          ),
        ),
      ),
    );
  }

  // 顶部装饰区域
  Widget _buildTopDecoration() {
    return SizedBox(
      height: 60,
      child: Stack(
        children: [
          // 标题
          const Positioned(
            bottom: 0,
            left: 0,
            child: Text(
              "我的",
              style: TextStyle(
                fontSize: AppTheme.fontSizeLarge,
                fontWeight: FontWeight.bold,
                color: AppTheme.textPrimaryColor,
              ),
            ),
          ),
        ],
      ),
    );
  }

  // 用户资料卡
  Widget _buildUserProfileCard() {
    return Container(
      margin: const EdgeInsets.symmetric(vertical: AppTheme.paddingXXL),
      child: Stack(
        clipBehavior: Clip.none,
        children: [
          Container(
            padding: const EdgeInsets.all(AppTheme.paddingXXL),
            decoration: BoxDecoration(
              gradient: const LinearGradient(
                begin: Alignment.topLeft,
                end: Alignment.bottomRight,
                colors: [Colors.white, Color(0xFFFAFBFF)],
              ),
              borderRadius: BorderRadius.circular(AppTheme.radiusXL),
              boxShadow: [
                BoxShadow(
                  color: AppTheme.primaryColor.withOpacity(0.1),
                  blurRadius: 20,
                  offset: const Offset(0, 8),
                ),
                BoxShadow(
                  color: Colors.white.withOpacity(0.8),
                  blurRadius: 20,
                  offset: const Offset(0, -4),
                ),
              ],
              border: Border.all(
                color: Colors.white.withOpacity(0.6),
                width: 1,
              ),
            ),
            child: Column(
              children: [
                // 头像区域
                Container(
                  width: 120,
                  height: 120,
                  decoration: BoxDecoration(
                    shape: BoxShape.circle,
                    gradient: AppTheme.primaryGradient,
                    boxShadow: [
                      BoxShadow(
                        color: AppTheme.primaryColor.withOpacity(0.3),
                        blurRadius: 20,
                        offset: const Offset(0, 8),
                      ),
                    ],
                  ),
                  child: Container(
                    margin: const EdgeInsets.all(4),
                    decoration: const BoxDecoration(
                      shape: BoxShape.circle,
                      color: Colors.white,
                    ),
                    child: ClipOval(
                      child: Image.asset(
                        _avatarPath,
                        fit: BoxFit.cover,
                        width: 112,
                        height: 112,
                        errorBuilder: (context, error, stackTrace) {
                          return Container(
                            decoration: BoxDecoration(
                              shape: BoxShape.circle,
                              gradient: AppTheme.primaryGradient,
                            ),
                            child: const Icon(
                              Icons.person,
                              size: 60,
                              color: Colors.white,
                            ),
                          );
                        },
                      ),
                    ),
                  ),
                ),
                const SizedBox(height: AppTheme.paddingXL),
                
                // 用户名
                ShaderMask(
                  shaderCallback: (bounds) => AppTheme.primaryGradient.createShader(bounds),
                  child: Text(
                    _userName,
                    style: const TextStyle(
                      fontSize: AppTheme.fontSizeTitle + 4,
                      fontWeight: FontWeight.bold,
                      color: Colors.white,
                    ),
                  ),
                ),
                const SizedBox(height: AppTheme.paddingS),
                
                // 邮箱
                Container(
                  padding: const EdgeInsets.symmetric(
                    horizontal: AppTheme.paddingL,
                    vertical: AppTheme.paddingS,
                  ),
                  decoration: BoxDecoration(
                    color: AppTheme.primaryColor.withOpacity(0.1),
                    borderRadius: BorderRadius.circular(AppTheme.radiusL),
                  ),
                  child: Text(
                    _userEmail,
                    style: const TextStyle(
                      fontSize: AppTheme.fontSizeL,
                      color: AppTheme.textSecondaryColor,
                      fontWeight: FontWeight.w500,
                    ),
                  ),
                ),
              ],
            ),
          ),
          Positioned(
            top: -10,
            right: -10,
            child: Material(
              color: Colors.white,
              shape: const CircleBorder(),
              elevation: 4.0,
              child: IconButton(
                icon: const Icon(Icons.edit, color: AppTheme.primaryColor),
                onPressed: () async {
                  final result = await Navigator.push(
                    context,
                    MaterialPageRoute(
                      builder: (context) => EditProfilePage(
                        currentName: _userName,
                        currentAvatarPath: _avatarPath,
                      ),
                    ),
                  );

                  if (result != null) {
                    setState(() {
                      _userName = result['name'];
                      _avatarPath = result['avatarPath'];
                    });
                  }
                },
              ),
            ),
          )
        ],
      ),
    );
  }

  // 统计概览
  Widget _buildStatsOverview() {
    final activeTasks = widget.tasks.where((task) => !task.isDeleted).toList();
    final totalTasks = activeTasks.length;
    final completedTasks = activeTasks.where((task) => task.isCompleted).length;
    final pendingTasks = totalTasks - completedTasks;
    final completionRate = totalTasks > 0 ? (completedTasks / totalTasks * 100) : 0;

    return Container(
      margin: const EdgeInsets.only(bottom: AppTheme.paddingXXL),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const Text(
            "任务概览",
            style: TextStyle(
              fontSize: AppTheme.fontSizeXL,
              fontWeight: FontWeight.bold,
              color: AppTheme.textPrimaryColor,
            ),
          ),
          const SizedBox(height: AppTheme.paddingL),
          Row(
            children: [
              Expanded(child: _buildStatCard("总任务", totalTasks.toString(), Icons.assignment_outlined, AppTheme.primaryGradient)),
              const SizedBox(width: AppTheme.paddingM),
              Expanded(child: _buildStatCard("已完成", completedTasks.toString(), Icons.check_circle_outline, AppTheme.successGradient)),
            ],
          ),
          const SizedBox(height: AppTheme.paddingM),
          Row(
            children: [
              Expanded(child: _buildStatCard("待完成", pendingTasks.toString(), Icons.pending_outlined, AppTheme.warningGradient)),
              const SizedBox(width: AppTheme.paddingM),
              Expanded(child: _buildStatCard("完成率", "${completionRate.toStringAsFixed(0)}%", Icons.trending_up_outlined, 
                completionRate >= 80 ? AppTheme.successGradient : completionRate >= 50 ? AppTheme.warningGradient : 
                const LinearGradient(colors: [Color(0xFFEF4444), Color(0xFFDC2626)]))),
            ],
          ),
        ],
      ),
    );
  }

  Widget _buildStatCard(String title, String value, IconData icon, LinearGradient gradient) {
    return Container(
      padding: const EdgeInsets.all(AppTheme.paddingL),
      decoration: BoxDecoration(
        gradient: const LinearGradient(
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
          colors: [Colors.white, Color(0xFFFAFBFF)],
        ),
        borderRadius: BorderRadius.circular(AppTheme.radiusL),
        boxShadow: AppTheme.softShadow,
        border: Border.all(
          color: Colors.white.withOpacity(0.6),
          width: 1,
        ),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Container(
            padding: const EdgeInsets.all(8),
            decoration: BoxDecoration(
              gradient: gradient,
              borderRadius: BorderRadius.circular(8),
            ),
            child: Icon(
              icon,
              color: Colors.white,
              size: 20,
            ),
          ),
          const SizedBox(height: AppTheme.paddingM),
          Text(
            value,
            style: const TextStyle(
              fontSize: AppTheme.fontSizeXL,
              fontWeight: FontWeight.bold,
              color: AppTheme.textPrimaryColor,
            ),
          ),
          Text(
            title,
            style: const TextStyle(
              fontSize: AppTheme.fontSizeS,
              color: AppTheme.textSecondaryColor,
              fontWeight: FontWeight.w500,
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildTaskCategories(BuildContext context) {
    final categories = widget.tasks.map((t) => t.category).toSet().toList();
    
    return Container(
      padding: const EdgeInsets.symmetric(vertical: AppTheme.paddingL),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const Padding(
            padding: EdgeInsets.symmetric(horizontal: AppTheme.paddingM),
            child: Text(
              "任务分类",
              style: TextStyle(
                fontSize: AppTheme.fontSizeXL,
                fontWeight: FontWeight.bold,
                color: AppTheme.textPrimaryColor,
              ),
            ),
          ),
          const SizedBox(height: AppTheme.paddingL),
          GridView.builder(
            shrinkWrap: true,
            physics: const NeverScrollableScrollPhysics(),
            gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
              crossAxisCount: 2,
              crossAxisSpacing: AppTheme.paddingM,
              mainAxisSpacing: AppTheme.paddingM,
              childAspectRatio: 2.5,
            ),
            itemCount: categories.length,
            itemBuilder: (context, index) {
              final category = categories[index];
              final count = widget.tasks.where((t) => t.category == category).length;
              final iconData = _getIconForCategory(category);
              final color = _getColorForCategory(category);

              return InkWell(
                onTap: () {
                  Navigator.push(
                    context,
                    MaterialPageRoute(
                      builder: (context) => CategoryTasksPage(
                        category: category,
                        allTasks: widget.tasks,
                      ),
                    ),
                  );
                },
                borderRadius: BorderRadius.circular(AppTheme.radiusL),
                child: Container(
                  padding: const EdgeInsets.all(AppTheme.paddingL),
                  decoration: BoxDecoration(
                    gradient: LinearGradient(
                      colors: [color.withOpacity(0.2), color.withOpacity(0.1)],
                      begin: Alignment.topLeft,
                      end: Alignment.bottomRight,
                    ),
                    borderRadius: BorderRadius.circular(AppTheme.radiusL),
                    boxShadow: [
                      BoxShadow(
                        color: color.withOpacity(0.15),
                        blurRadius: 10,
                        offset: const Offset(2, 2),
                      ),
                    ],
                    border: Border.all(
                      color: color.withOpacity(0.3),
                      width: 1,
                    ),
                  ),
                  child: Row(
                    children: [
                      Container(
                        padding: const EdgeInsets.all(AppTheme.paddingS),
                        decoration: BoxDecoration(
                          color: Colors.white.withOpacity(0.8),
                          shape: BoxShape.circle,
                        ),
                        child: Icon(iconData, color: color, size: 24),
                      ),
                      const SizedBox(width: AppTheme.paddingM),
                      Expanded(
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text(
                              category,
                              style: const TextStyle(
                                fontSize: AppTheme.fontSizeL,
                                fontWeight: FontWeight.bold,
                                color: Colors.white,
                                shadows: [
                                   Shadow(
                                    color: Colors.black26,
                                    offset: Offset(1, 1),
                                    blurRadius: 2,
                                  ),
                                ],
                              ),
                              overflow: TextOverflow.ellipsis,
                            ),
                            const SizedBox(height: AppTheme.paddingXS),
                            Text(
                              "$count 个任务",
                              style: TextStyle(
                                fontSize: AppTheme.fontSizeS,
                                color: Colors.white.withOpacity(0.9),
                              ),
                            ),
                          ],
                        ),
                      ),
                    ],
                  ),
                ),
              );
            },
          ),
        ],
      ),
    );
  }

  IconData _getIconForCategory(String category) {
    switch (category) {
      case 'Work':
        return Icons.work_outline;
      case 'Personal':
        return Icons.person_outline;
      case 'Meeting':
        return Icons.people_outline;
      case 'Shopping':
        return Icons.shopping_cart_outlined;
      case 'Health':
        return Icons.favorite_border;
      case 'Study':
        return Icons.school_outlined;
      case 'Events':
        return Icons.event_available_outlined;
      default:
        return Icons.task_alt_outlined;
    }
  }

  Color _getColorForCategory(String category) {
    switch (category) {
      case 'Work':
        return Colors.purple;
      case 'Personal':
        return Colors.blue;
      case 'Meeting':
        return Colors.orange;
      case 'Events':
        return Colors.pink;
      case 'Shopping':
        return Colors.green;
      case 'Health':
        return Colors.red;
      case 'Study':
        return Colors.indigo;
      default:
        return Colors.grey.shade700;
    }
  }

  // 设置区域
  Widget _buildSettingsSection() {
    return Container(
      margin: const EdgeInsets.symmetric(vertical: AppTheme.paddingL),
      decoration: BoxDecoration(
        color: Colors.white.withOpacity(0.8),
        borderRadius: BorderRadius.circular(AppTheme.radiusXL),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.04),
            blurRadius: 10,
            offset: const Offset(0, 4),
          ),
        ],
      ),
      child: ClipRRect(
        borderRadius: BorderRadius.circular(AppTheme.radiusXL),
        child: Material(
          color: Colors.transparent,
          child: Column(
            children: [
              _buildSettingsGroup(
                icon: Icons.settings_outlined,
                title: "基础功能",
                children: [
                  _buildSettingsItem(
                    icon: Icons.person_outline,
                    title: "编辑个人资料",
                    onTap: () => _editProfile(context),
                  ),
                  _buildSettingsItem(
                    icon: Icons.notifications_none_outlined,
                    title: "通知设置",
                    onTap: () => _navigateTo(NotificationSettingsPage()),
                  ),
                ],
              ),
              _buildSettingsGroup(
                icon: Icons.info_outline,
                title: "其他",
                children: [
                  _buildSettingsItem(
                    icon: Icons.feedback_outlined,
                    title: "发送反馈",
                    onTap: () => _launchFeedbackURL(),
                  ),
                  _buildSettingsItem(
                    icon: Icons.info_outline,
                    title: "关于我们",
                    onTap: () => _navigateTo(AboutUsPage()),
                  ),
                  _buildSettingsItem(
                    icon: Icons.exit_to_app,
                    title: "退出应用",
                    onTap: () => SystemNavigator.pop(),
                    isDestructive: true,
                  ),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildSettingsGroup({
    required IconData icon,
    required String title,
    required List<Widget> children,
  }) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Padding(
          padding: const EdgeInsets.symmetric(
            horizontal: AppTheme.paddingL,
            vertical: AppTheme.paddingM,
          ),
          child: Row(
            children: [
              Icon(icon, color: AppTheme.textSecondaryColor),
              const SizedBox(width: AppTheme.paddingL),
              Text(
                title,
                style: const TextStyle(
                  fontSize: AppTheme.fontSizeL,
                  fontWeight: FontWeight.w500,
                  color: AppTheme.textPrimaryColor,
                ),
              ),
            ],
          ),
        ),
        ...children,
      ],
    );
  }

  Widget _buildSettingsItem({
    required IconData icon,
    required String title,
    required VoidCallback onTap,
    Widget? trailing,
    bool isDestructive = false,
  }) {
    return Material(
      color: Colors.transparent,
      child: InkWell(
        onTap: onTap,
        borderRadius: BorderRadius.circular(AppTheme.radiusL),
        child: Padding(
          padding: const EdgeInsets.symmetric(
            horizontal: AppTheme.paddingL,
            vertical: AppTheme.paddingM,
          ),
          child: Row(
            children: [
              Icon(icon, color: isDestructive ? AppTheme.errorColor : AppTheme.textSecondaryColor),
              const SizedBox(width: AppTheme.paddingL),
              Expanded(
                child: Text(
                  title,
                  style: TextStyle(
                    fontSize: AppTheme.fontSizeL,
                    fontWeight: FontWeight.w500,
                    color: isDestructive ? AppTheme.errorColor : AppTheme.textPrimaryColor,
                  ),
                ),
              ),
              if (trailing != null) trailing else const Icon(Icons.arrow_forward_ios, size: 16, color: AppTheme.textSecondaryColor),
            ],
          ),
        ),
      ),
    );
  }

  void _launchFeedbackURL() async {
    final Uri feedbackUrl = Uri.parse('https://forms.gle/your_feedback_form_url'); // 请替换为您自己的表单链接

    if (await canLaunchUrl(feedbackUrl)) {
      await launchUrl(feedbackUrl, mode: LaunchMode.externalApplication);
    } else {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('无法打开浏览器')),
      );
    }
  }

  void _editProfile(BuildContext context) async {
    final result = await Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => EditProfilePage(
          currentName: _userName,
          currentAvatarPath: _avatarPath,
        ),
      ),
    );

    if (result != null) {
      setState(() {
        _userName = result['name'];
        _avatarPath = result['avatarPath'];
      });
    }
  }

  void _navigateTo(Widget page) {
    Navigator.push(context, MaterialPageRoute(builder: (context) => page));
  }
} 